package com.company.huisuo.biz.dialog

import android.app.Activity
import android.widget.ArrayAdapter
import androidx.core.view.isVisible
import com.company.huisuo.R
import com.company.huisuo.base.BaseCenterPopupView
import com.company.huisuo.biz.bean.GamePlanBean
import com.company.huisuo.databinding.DialogSelectScriptBinding
import com.company.huisuo.ext.toast
import com.company.huisuo.repository.GamePlanRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 选择剧本
 */
class SelectScriptDialog(activity: Activity,gameType: String) : BaseCenterPopupView<DialogSelectScriptBinding>(
    activity
) {

    var onConfirmListener: ((GamePlanBean) -> Unit)? = null
    override val getLayoutId: Int
        get() = R.layout.dialog_select_script
    override val getViewBinding: DialogSelectScriptBinding
        get() = DialogSelectScriptBinding.bind(contentView)

    private var gamePlanList: List<GamePlanBean> = emptyList()
    private val gameType: String = gameType
    
    private val gamePlanRepository by lazy {
        GamePlanRepository()
    }
    
    override fun initData() {
        mBinding.apply {
            ivClose.setOnClickListener {
                dismiss()
            }
            tvOk.setOnClickListener {
                val selectedPosition = spinnerScript.selectedItemPosition
                val selectedItem =  gamePlanList[selectedPosition]
                onConfirmListener?.invoke(selectedItem)
                dismiss()
            }

        }
        loadGamePlans(gameType)
    }
    
    /**
     * 加载游戏剧本数据
     */
    private fun loadGamePlans(gameType: String) {
        GlobalScope.launch(Dispatchers.Main) {
            try {
                val result = gamePlanRepository.getGamePlanList(gameType)
                if (result.isSuccess) {
                    val gamePlans = result.getOrThrow()
                    if (gamePlans.isNotEmpty()) {
                        gamePlanList = gamePlans
                        
                        // 创建适配器，显示planName
                        val planNames = gamePlanList.map { it.planName }
                        val adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, planNames)
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                        
                        mBinding.spinnerScript.adapter = adapter
                    } else {
                        // 如果API返回空数据，使用本地默认数据作为fallback
                        showDefaultData()
                    }
                } else {
                    // 网络请求失败，使用本地默认数据作为fallback
                    showDefaultData()
                    "网络请求失败，显示默认数据".toast()
                }
            } catch (e: Exception) {
                // 异常处理，使用本地默认数据作为fallback
                showDefaultData()
                "数据加载失败，显示默认数据".toast()
            }
        }
    }
    
    /**
     * 显示默认数据（fallback方案）
     */
    private fun showDefaultData() {
        val defaultList = arrayListOf<String>("欲望暧昧牌", "激情暧昧牌")
        val adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, defaultList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        mBinding.spinnerScript.adapter = adapter
    }


}